package net.homeip.jcperera.webinfo.beans;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TypedQuery;

import net.homeip.jcperera.nu.core.boot.Boot;
import net.homeip.jcperera.nu.core.msg.BaseMessage;
import net.homeip.jcperera.nu.core.msg.MessageBagRequest;
import net.homeip.jcperera.nu.core.utils.DateUtil;
import net.homeip.jcperera.webinfo.ScanProfile;
import net.homeip.jcperera.webinfo.ScanProfileParameter;
import net.homeip.jcperera.webinfo.WebInfoSite;

import org.primefaces.event.SelectEvent;

@ManagedBean
@ViewScoped
public class ScanProfileBean implements Serializable
{
    private static final long serialVersionUID = -3299812581447743191L;

    private ScanProfile       scanProfile;

    public ScanProfileBean()
    {
        scanProfile = new ScanProfile();
    }

    public List<ScanProfile> getScanProfiles()
    {
        List<ScanProfile> scanProfiles = new ArrayList<ScanProfile>();

        if (scanProfile != null && scanProfile.getSite() != null)
        {
            scanProfiles.addAll(scanProfile.getSite().getScanProfiles());
        }
        return scanProfiles;
    }

    public List<ScanProfile> getAllScanProfiles()
    {
        List<ScanProfile> scanProfiles = new ArrayList<ScanProfile>();
        EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
        EntityManager entityManager = (EntityManager) emf.createEntityManager();
        entityManager.getTransaction().begin();
        TypedQuery<ScanProfile> scpQuery = entityManager.createQuery("SELECT OBJECT(scp) FROM ScanProfile scp",
                ScanProfile.class);
        scanProfiles = scpQuery.getResultList();
        entityManager.getTransaction().commit();
        entityManager.close();
        return scanProfiles;
    }

    public void saveScanProfile(ActionEvent actionEvent)
    {
        saveScanProfile();
    }

    public String saveScanProfile()
    {
        if (scanProfile != null)
        {
            EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
            EntityManager entityManager = (EntityManager) emf.createEntityManager();
            entityManager.getTransaction().begin();
            if (scanProfile.getEntityid() != null && scanProfile.getEntityid().length() > 0)
                scanProfile = entityManager.merge(scanProfile);
            entityManager.persist(scanProfile);
            entityManager.getTransaction().commit();
            entityManager.getEntityManagerFactory().getCache().evictAll();
            entityManager.close();
            MessageBagRequest messageBagRequest = new MessageBagRequest();
            messageBagRequest.addInformationalMessage("nu.core.entity.saved.ok", BaseMessage.FRIENDLINESS_FRIENDLY);
            messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
        }
        return "edit.xhtml?faces-redirect=true&entityid=" + this.getEntityid();
    }

    public void deleteScanProfile(ActionEvent actionEvent)
    {
        deleteScanProfile();
    }

    public String deleteScanProfile()
    {
        if (scanProfile != null)
        {
            MessageBagRequest messageBagRequest = new MessageBagRequest();
            String entityid = scanProfile.getEntityid();
            if (entityid != null && entityid.trim().length() > 0)
            {
                EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
                EntityManager entityManager = (EntityManager) emf.createEntityManager();
                entityManager.getTransaction().begin();
                scanProfile = entityManager.merge(scanProfile);
                entityManager.remove(scanProfile);
                messageBagRequest.addInformationalMessage("nu.core.entity.deleted.ok",
                        BaseMessage.FRIENDLINESS_FRIENDLY);
                entityManager.getTransaction().commit();
                entityManager.getEntityManagerFactory().getCache().evictAll();
                entityManager.close();
            }
            messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
        }
        return "/pages/scanprofile/list.xhtml?faces-redirect=true";
    }

    public String getEntityid()
    {
        return scanProfile.getEntityid();
    }

    public void setEntityid(String entityid)
    {
        MessageBagRequest messageBagRequest = new MessageBagRequest();
        if (entityid != null)
        {
            EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
            EntityManager entityManager = (EntityManager) emf.createEntityManager();
            entityManager.getTransaction().begin();
            ScanProfile scanProfile = null;
            TypedQuery<ScanProfile> wisQuery = entityManager.createQuery(
                    "SELECT OBJECT(scp) FROM ScanProfile scp WHERE scp.entityid = :entityid", ScanProfile.class);
            wisQuery.setParameter("entityid", entityid);
            scanProfile = wisQuery.getSingleResult();
            if (scanProfile == null)
            {
                Hashtable<String, String> extensions = new Hashtable<String, String>();
                extensions.put("id", entityid);
                extensions.put("description", "Entity not found on database");
                messageBagRequest.addErrorMessage("nu.core.entity.type.load.error", BaseMessage.FRIENDLINESS_FRIENDLY,
                        extensions);
            }
            else this.scanProfile = scanProfile;
            entityManager.getTransaction().commit();
            entityManager.close();
        }
        messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
    }

    public String getParentid()
    {
        return ((scanProfile != null && scanProfile.getSite() != null) ? scanProfile.getSite().getEntityid() : null);
    }

    public void setParentid(String entityid)
    {
        MessageBagRequest messageBagRequest = new MessageBagRequest();
        if (entityid != null)
        {
            EntityManagerFactory emf = Boot.getSystem().getPersistence().getEntityManagerFactory();
            EntityManager entityManager = (EntityManager) emf.createEntityManager();
            entityManager.getTransaction().begin();
            WebInfoSite webInfoSite = null;
            TypedQuery<WebInfoSite> wisQuery = entityManager.createQuery(
                    "SELECT OBJECT(wis) FROM WebInfoSite wis WHERE wis.entityid = :entityid", WebInfoSite.class);
            wisQuery.setParameter("entityid", entityid);
            webInfoSite = wisQuery.getSingleResult();
            if (webInfoSite == null)
            {
                Hashtable<String, String> extensions = new Hashtable<String, String>();
                extensions.put("id", entityid);
                extensions.put("description", "Entity not found on database");
                messageBagRequest.addErrorMessage("nu.core.entity.type.load.error", BaseMessage.FRIENDLINESS_FRIENDLY,
                        extensions);
            }
            else this.scanProfile.setSite(webInfoSite);
            entityManager.getTransaction().commit();
            entityManager.close();
        }
        messageBagRequest.addAllMessagesToFacesContext(FacesContext.getCurrentInstance());
    }

    public void onRowSelect(SelectEvent event)
    {
        try
        {
            FacesContext.getCurrentInstance().getExternalContext()
                    .redirect("../scanprofile/edit.xhtml?entityid=" + scanProfile.getEntityid());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public String getName()
    {
        return scanProfile.getName();
    }

    public void setName(String name)
    {
        scanProfile.setName(name);
    }

    public Integer getPeriodicity()
    {
        return scanProfile.getPeriodicity();
    }

    public void setPeriodicity(Integer periodicity)
    {
        scanProfile.setPeriodicity(periodicity);
    }

    public DateUtil.Periodicity getPeriodicityUnit()
    {
        return scanProfile.getPeriodicityUnit();
    }

    public void setPeriodicityUnit(DateUtil.Periodicity periodicityUnit)
    {
        scanProfile.setPeriodicityUnit(periodicityUnit);
    }

    public Boolean getIsRunning()
    {
        return scanProfile.getIsRunning();
    }

    public void setIsRunning(Boolean isRunning)
    {
        scanProfile.setIsRunning(isRunning);
    }

    public Integer getFetchNextDelay()
    {
        return scanProfile.getFetchNextDelay();
    }

    public void setFetchNextDelay(Integer fetchNextDelay)
    {
        scanProfile.setFetchNextDelay(fetchNextDelay);
    }

    public DateUtil.Periodicity getFetchNextDelayUnit()
    {
        return scanProfile.getFetchNextDelayUnit();
    }

    public void setFetchNextDelayUnit(DateUtil.Periodicity fetchNextDelayUnit)
    {
        scanProfile.setFetchNextDelayUnit(fetchNextDelayUnit);
    }

    public Integer getTolerance()
    {
        return scanProfile.getTolerance();
    }

    public void setTolerance(Integer tolerance)
    {
        scanProfile.setTolerance(tolerance);
    }

    public DateUtil.Periodicity getToleranceUnit()
    {
        return scanProfile.getToleranceUnit();
    }

    public void setToleranceUnit(DateUtil.Periodicity toleranceUnit)
    {
        scanProfile.setToleranceUnit(toleranceUnit);
    }

    public Calendar getLastRunStarted()
    {
        return scanProfile.getLastRunStarted();
    }

    public void setLastRunStarted(Calendar lastRunStarted)
    {
        this.setLastRunStarted(lastRunStarted);
    }

    public Calendar getLastRunStopped()
    {
        return scanProfile.getLastRunStopped();
    }

    public void setLastRunStopped(Calendar lastRunStopped)
    {
        scanProfile.setLastRunStopped(lastRunStopped);
    }

    public Integer getHowManyUp()
    {
        return scanProfile.getHowManyUp();
    }

    public void setHowManyUp(Integer howManyUp)
    {
        scanProfile.setHowManyUp(howManyUp);
    }

    public Integer getHowManyDown()
    {
        return scanProfile.getHowManyDown();
    }

    public void setHowManyDown(Integer howManyDown)
    {
        scanProfile.setHowManyDown(howManyDown);
    }

    public WebInfoSite getSite()
    {
        return scanProfile.getSite();
    }

    public void setSite(WebInfoSite site)
    {
        scanProfile.setSite(site);
    }

    public Set<ScanProfileParameter> getScanProfileParameters()
    {
        return scanProfile.getScanProfileParameters();
    }
    
    public ScanProfile getSelectedScanProfile()
    {
        return this.scanProfile;
    }
    
    public void setSelectedScanProfile(ScanProfile scanProfile)
    {
        this.scanProfile = scanProfile;
    }
    
    public DateUtil.Periodicity[] getPeriodicities()
    {
        return DateUtil.Periodicity.values();
    }
}
